__version__ = '0.0.1';

'use strict';

startup()

function startup() {
    $('#connectButton').click(connect);
    $('#disconnectButton').click(disconnect);
}

let core_pc;
function connect(e) {

    core_pc = new Data_PC(id = 'core_pc');
    core_pc.onopen = (e) => {
        $('#connectButton').attr("disabled",true);
        $('#disconnectButton').attr("disabled",false);
        create_message();
    };
    core_pc.onclose = (e) => {
        $('#connectButton').attr("disabled",false);
        $('#disconnectButton').attr("disabled",true);
    };
    core_pc.DataRecivers = {};
    core_pc.onMessage = (event) => {
        for (name in DataRecivers){
            core_pc.DataRecivers[name](event.data);
        }
    }
}

function disconnect() {
    // Close the RTCPeerConnections
    core_pc.close();
    core_pc = null;
}

function create_message() {
    append_html(`
    <button id="openMessage" >openMessage</button>
    <button id="closeMessage" disabled>closeMessage</button>
    `);
    $('#openMessage').click(() => {

        let message_pc = new Data_PC(id = 'message_pc', exchange_methods = _diy_exchange_methods);


        function onopen(e){
            $('#message').attr("disabled",false);
            $('#message').focus();
            $('#sendButton').attr("disabled",false);
            $('#openMessage').attr("disabled",true);
            $('#closeMessage').attr("disabled",false);

        };
        function onclose(e){
            $('#message').val("")
            $('#message').attr("disabled",true);
            $('#sendButton').attr("disabled",true);
            $('#openMessage').attr("disabled",false);
            $('#closeMessage').attr("disabled",true);
        };

        function onMessage(event) {
            $('#receivebox').append($("<p></p>").text(event.data))
        }

        _diy_exchange_methods = {
            'init':(self) = {
                core_pc.register('message_pc',(data) => {
                    
                })
            },
            'send_key':(self) => {

            }

        }

        
        
        function sendMessage() {
            let message = $('#message').val();
            message_pc.send(message);
            $('#message').val('');
            $('#message').focus();
        }

        append_html(`
            <div>
                <label for="message">Enter a message:
                    <input type="text" id="message" placeholder="Message text"
                        inputmode="latin" size=60 maxlength=120 disabled>
                </label>
                <button id="sendButton" disabled>Send</button>
            </div>
            <div id="receivebox">
                <p>Messages received:</p>
            </div>`);

        $('#sendButton').click(sendMessage);



        $('#closeMessage').click((event) => {
            // Close the RTCPeerConnections
            message_pc.close();
            message_pc = null;
        })
    });
}